package com.hunan.chinamobile.manager;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.chinamobile.core.BaseController;
import com.hunan.chinamobile.core.Result;
import com.hunan.chinamobile.core.ResultGenerator;
import com.hunan.chinamobile.dto.DeviceDataDTO;
import com.hunan.chinamobile.dto.UserDTO;
import com.hunan.chinamobile.service.DeviceDataService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/data")
public class DataController extends BaseController{


    @Resource
    private DeviceDataService deviceDataService;

    @GetMapping
    public Result list(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam(required = false)String cityId,
                       @RequestParam(required = false)String bsId,
                       @RequestParam(required = false)String deviceId,
                       @RequestParam(required = false)Integer type,
                       @RequestParam(required = false)Long startTime,
                       @RequestParam(required = false)Long endTime,
                       @RequestParam(name = "page", defaultValue = "1") Integer page,
                       @RequestParam(name = "size", defaultValue = "20") Integer size){


        if(StringUtils.isEmpty(cityId)){
            cityId = getCityId(request, response);
        }
        String startDate = "";
        String endDate = "";
        if(startTime != null && endTime != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startDate = sdf.format(new Date(startTime));
            endDate = sdf.format(new Date(endTime));
        }
        PageHelper.startPage(page,size);
        List<DeviceDataDTO> dds = deviceDataService.findList(deviceId,bsId,cityId,type,startDate,endDate);
        PageInfo<DeviceDataDTO> pageInfo = new PageInfo<>(dds);

        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(required = false)String cityId,
                         @RequestParam(required = false)String bsId,
                         @RequestParam(required = false)String deviceId,
                         @RequestParam(required = false)Integer type,
                         @RequestParam(required = false)Long startTime,
                         @RequestParam(required = false)Long endTime){
        if(StringUtils.isEmpty(cityId)){
            UserDTO userDTO = getUser(request, response);
            cityId = userDTO != null ? userDTO.getCityId():"";
        }
        String startDate = "";
        String endDate = "";
        if(startTime != null && endTime != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            startDate = sdf.format(new Date(startTime));
            endDate = sdf.format(new Date(endTime));
        }
        List<DeviceDataDTO> dds = deviceDataService.findList(deviceId,bsId,cityId,type,startDate,endDate);
        if(dds == null) return;
        downloadHandler(response,dds);
    }

    private void downloadHandler(HttpServletResponse response,List<DeviceDataDTO> dds){
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle cellStyle = wb.createCellStyle();
        // 指定单元格居中对齐
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时换行
        cellStyle.setWrapText(true);

        HSSFFont cf = wb.createFont();
        cf.setBold(true);
        cf.setFontHeightInPoints((short) 12);
        cf.setFontName("宋体");
        cellStyle.setFont(cf);
        String[] hs = new String[]{"设备名称","基站名称","参数名称","参数值","采集时间"};

        HSSFSheet sheet = wb.createSheet("历史数据");
        int rowIndex = 0;
        HSSFRow r1 = sheet.createRow(rowIndex);
        r1.setHeightInPoints(30);
        for (int i = 0; i < hs.length; i++) {
            HSSFCell c1 = r1.createCell(i);
            c1.setCellValue(new HSSFRichTextString(hs[i]));
            c1.setCellStyle(cellStyle);
            int w = 25;
            if (i == 1) w = 30;
            sheet.setColumnWidth(i, w * 256);
        }

        HSSFCellStyle cs = wb.createCellStyle();
        // 指定单元格居中对齐
        cs.setAlignment(HorizontalAlignment.CENTER);
        // 指定单元格垂直居中对齐
        cs.setVerticalAlignment(VerticalAlignment.CENTER);
        // 指定当单元格内容显示不下时换行
        cs.setWrapText(true);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(DeviceDataDTO d : dds){
            rowIndex++;
            HSSFRow bsRow = sheet.createRow(rowIndex);
            bsRow.setHeightInPoints(20);

            setData(bsRow,cs,0,d.getDeviceName());
            setData(bsRow,cs,1,d.getBaseStationName());
            setData(bsRow,cs,2,d.getParam());
            String sv = d.getShowValue();
            if(sv.equals("1")) sv = "正常";
            else if(sv.equals("0")) sv = "异常";
            setData(bsRow,cs,3,sv);
            setData(bsRow,cs,4,sdf.format(d.getCreatedAt()));
        }

        String fileName = sdf.format(new Date())+"历史数据.xls";
        System.out.println("fileName:" + fileName);
        try {
            fileName = new String(fileName.getBytes("gb2312"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.reset();
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 指定下载的文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            OutputStream output = response.getOutputStream();
            wb.write(output);
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setData(HSSFRow bsRow,HSSFCellStyle cs,int colIndex,String v){
        HSSFCell bc1 = bsRow.createCell(colIndex);
        bc1.setCellValue(new HSSFRichTextString(v));
        bc1.setCellStyle(cs);
    }
}
